<template>
  <div>
    <!-- 用户列表页面 -->
    <!-- 卡片 -->
    <el-card class="box-card">
      <!--  -->
      <div class="text item">
        <div>
          <el-input
            placeholder="请输入内容"
            v-model="input1"
            class="input-with-select"
            clearable
            @clear="eli"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="seek"
            ></el-button>
          </el-input>
          <el-button type="danger" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </div>
      </div>
      <!-- 表格 :data="tableData"-->
      <el-table :data="$store.state.list" border style="width: 100%">
        <el-table-column prop="sort" label="#" width="50"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="150">
        </el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#dcdfe6"
              @change="swc(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="com(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="open(scope.row)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-s-tools"
              circle
              @click="allot(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 添加弹框 -->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
        <!-- 验证表单 -->
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input class="inpu" v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input class="inpu" v-model="ruleForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input class="inpu" v-model="ruleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input
              class="inpu"
              v-model="ruleForm.mobile"
              oninput="value=value.replace(/[^\d]/g,'');if(value.length > 11)value = value.slice(0, 11)"
            ></el-input>
          </el-form-item>
        </el-form>
        <!--  -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="danger" @click="submitForm('ruleForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 修改弹框 -->
      <el-dialog title="修改用户" :visible.sync="dialogVisible2" width="50%">
        <!-- 修改表单 -->
        <el-form
          :model="ruleForm2"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名">
            <el-input
              class="inpu"
              v-model="ruleForm2.username"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input class="inpu" v-model="ruleForm2.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input class="inpu" v-model="ruleForm2.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!--  -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="Okcom">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色弹框 -->
      <el-dialog title="角色分配" :visible.sync="dialogVisible3" width="50%">
        <p class="p1">当前的用户：{{ cutlist.username }}</p>
        <p class="p1">当前的角色：{{ cutlist.role_name }}</p>
        <span>分配新角色：</span>
        <el-select v-model="role_id" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="reset">取 消</el-button>
          <el-button type="primary" @click="okAll">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import {
  getList,
  getadd,
  getstatus,
  getSeek,
  getcom,
  Delete,
  getAll,
  roleList,
} from "@/utils/api";
export default {
  name: "APP",
  data() {
    return {
      input1: "", //搜索输入框
      total: 0, // 数据总条数
      pagenum: 1, //当前页码
      pagesize: 5, //每页显示条数
      dialogVisible: false, //添加弹框默认状态
      ruleForm: {
        username: "", //用户名
        password: "", //密码
        email: "", //邮箱
        mobile: "", //手机号
      },

      ruleForm2: {
        username: "", //用户名
        email: "", //邮箱
        mobile: "", //手机
      },

      value: false, //开关状态
      dialogVisible2: false, //修改弹框默认状态
      dialogVisible3: false, //分配角色弹框默认状态

      role_id: "", //用户选中的角色id

      options: [], //角色列表
      cutlist: {}, //保存正在操作的那个用户信息
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名长度在 3 ~ 10 个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码长度在 6 ~ 15 个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            type: "email",
            message: "请输入合法的邮箱",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 11, message: "请输入合法的手机号", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    handleSizeChange(val) {
      //每页多少条
      //   console.log(`每页 ${val} 条`);
      this.pagesize = val;
      this.gets();
    },
    handleCurrentChange(val) {
      //当前页码
      //   console.log(`当前页: ${val}`);
      this.pagenum = val;
      this.gets();
    },

    gets() {
      //请求数据方法
      const queryInfo = {
        query: "",
        pagenum: this.pagenum,
        pagesize: this.pagesize,
      };
      getList(queryInfo).then((res) => {
        // console.log(res);
        res.data.users.forEach((item, index) => {
          item.sort = index + 1;
        });
        this.$store.commit("clear", res.data.users);
        this.total = res.data.total;
      });
    },

    submitForm(formName) {
      //确定添加
      this.$refs[formName].validate((valid) => {
        if (valid) {
          getadd(this.ruleForm).then((res) => {
            console.log(res);
            if (res.meta.status == 201) {
              this.$message({
                message: "添加用户成功!",
                type: "success",
              });
              this.gets();
              this.dialogVisible = false;
            }
          });
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },

    // 状态切换
    swc(val) {
      const params = {
        uId: val.id,
        type: val.mg_state,
      };
      getstatus(params).then((res) => {
        // console.log(res);
        if (res.meta.status == 200) {
          this.$message({
            message: "更新用户状态成功！",
            type: "success",
          });
        }
      });
    },

    seek() {
      //搜索查询
      if (this.input1 != "") {
          this.$store.commit("seek", this.input1);
      }
    },

    eli() {
      //清空搜索输入框触发的事件
      this.gets();
    },

    com(val) {
      //编辑
      this.dialogVisible2 = true;
      this.ruleForm2 = val;
    },

    Okcom() {
      //确定编辑
      const params = {
        id: this.ruleForm2.id,
        email: this.ruleForm2.email,
        mobile: this.ruleForm2.mobile,
      };
      //关闭弹框
      this.dialogVisible2 = false;
      getcom(params).then((res) => {
        // console.log(res);
        if (res.meta.status == 200) {
          this.$message({
            message: "更新用户信息成功！",
            type: "success",
          });
        } else {
          this.$message({
            message: res.meta.msg,
            type: "warning",
          });
        }
      });
    },

    open(val) {
      //删除
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const params = {
            id: val.id,
          };
          Delete(params).then((res) => {
            console.log(res);
            if (res.meta.status == 400) {
              this.$message.error("删除用户失败！");
            } else {
              this.$message({
                type: "success",
                message: "删除用户成功!",
              });
              this.gets();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    allot(val) {
      //分配角色按钮
      //分配弹窗显示
      this.dialogVisible3 = true;
      //保存当前点击的用户信息
      this.cutlist = val;

      //请求角色列表
      roleList().then((res) => {
        // console.log(res);
        this.options = res.data;
      });
    },

    okAll() {
      //确定分配
      //当用户点击确定按钮之后
      //判断用户是否选择了需要分配的角色
      if (!this.role_id) {
        return this.$message.error("请选择要分配的角色!");
      }

      const params = {
        id: this.cutlist.id,
        rid: this.role_id,
      };
      //  发送请求，分配角色
      getAll(params).then((res) => {
        //判断状态，分配不成功就提示
        if (res.meta.status !== 200) return this.$message.error("分配角色失败");

        this.$message({
          message: "更新角色成功",
          type: "success",
        });
        this.gets();
        this.dialogVisible3 = false;
        this.role_id = "";
        this.cutlist = {};
      });
    },

    reset() {
      //取消重置
      this.role_id = "";
      this.cutlist = {};
      this.dialogVisible3 = false;
    },
  },

  created() {
    this.gets();
  },
  mounted() {},
};
</script>
<style lang="scss" scoped>
.box-card {
  margin-top: 15px;
  .input-with-select {
    width: 330px;
    margin-right: 20px;
  }
  .el-table {
    margin-top: 15px;
  }
}
::v-deep .el-form-item__label {
  transform: translateX(-30px);
}
.inpu {
  width: 106%;
  transform: translateX(-30px);
}
::v-deep .el-form-item__error {
  transform: translateX(-30px);
}
.p1 {
  margin-bottom: 20px;
}
</style>
